﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DVForm
{
    public partial class FormView : Form
    {
        string sql = string.Empty;
        GMS.Core.Config.DBInfo _db {get;set;}

        string _tableName = string.Empty;
        
        M.Dao.Client.DBRepository dbr = null;

        public FormView(GMS.Core.Config.DBInfo db,string tableName)
        {
            InitializeComponent();
            _db = db;
            _tableName = tableName;

            sql = "select * from {0} ";
            sql = string.Format(sql,tableName);
            
            txtSQL.Text = sql;

            dbr = new M.Dao.Client.DBRepository(_db.Url, _db.Name, _db.AccessToken);

            this.Text = _tableName;

            this.Load += FormView_Load;
        }

        void FormView_Load(object sender, EventArgs e)
        {
            btnSearch.PerformClick();

        }
        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            sql = txtSQL.Text;

            var result = dbr.Query(sql, 1, dataGridViewPaging1.MaxRecords);

            dataGridViewPaging1.Initialize(result.Total);


            var dt = DicToTable(result.Items);

            dataGridViewPaging1.DataSource =dt;
        }
        
        public static DataTable DicToTable(Dictionary<string, object>[] dicDeps)
        {
            DataTable dt = new DataTable();

            if (dicDeps == null || dicDeps.Length == 0)
                return dt;

            foreach (var colName in dicDeps[0].Keys)
            {   
                dt.Columns.Add(colName, typeof(object));
            }

            foreach (Dictionary<string, object> dicDep in dicDeps)
            {
                DataRow dr = dt.NewRow();
                foreach (KeyValuePair<string, object> item in dicDep)
                {
                    if (dt.Columns.Contains(item.Key) == false)
                    {
                        dt.Columns.Add(item.Key, typeof(object));
                    }
                    dr[item.Key] = item.Value;
                }
                dt.Rows.Add(dr);
            }
           
            return dt;
        }

        private void dataGridViewPaging1_RequestQueryData(object sender, In.Sontx.SimpleDataGridViewPaging.RequestQueryDataEventArgs e)
        {
            var pageNo = e.PageOffset / e.MaxRecords + 1;

            var result = dbr.Query(sql, pageNo, dataGridViewPaging1.MaxRecords);
            
            var dt = DicToTable(result.Items);

            dataGridViewPaging1.DataSource = dt;
        }

    }
}
